﻿using Abp.Threading;
using LeadThing.AbpZeroTemplate.Areas;
using LeadThing.AbpZeroTemplate.Areas.Dtos;
using LeadThing.AbpZeroTemplate.Authorization.Roles;
using LeadThing.AbpZeroTemplate.Authorization.Roles.Dto;
using LeadThing.AbpZeroTemplate.CallPolices;
using LeadThing.AbpZeroTemplate.CallPolices.Dtos;
using LeadThing.AbpZeroTemplate.DisputeInformations;
using LeadThing.AbpZeroTemplate.DisputeInformations.Dtos;
using LeadThing.AbpZeroTemplate.Web.Models.Home;
using LeadThing.AbpZeroTemplate.Web.Session;
using LeadThing.AbpZeroTemplate.Web.WebReference;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using LeadThing.AbpZeroTemplate.Authorization.Users;
using LeadThing.AbpZeroTemplate.SpecialPersons;
using LeadThing.AbpZeroTemplate.LawsRegulationses;
using LeadThing.AbpZeroTemplate.Authorization.Users.Dto;
using LeadThing.AbpZeroTemplate.LawsRegulationses.Dtos;
using LeadThing.AbpZeroTemplate.SpecialPersons.Dtos;
using LeadThing.AbpZeroTemplate.CameraManages.Dtos;
using LeadThing.AbpZeroTemplate.CameraManages;
using LeadThing.AbpZeroTemplate.UserTrajectorys;
using LeadThing.AbpZeroTemplate.UserTrajectorys.Dtos;
using LeadThing.AbpZeroTemplate.BasicPersons;
using LeadThing.AbpZeroTemplate.BasicPersons.Dtos;
using LeadThing.AbpZeroTemplate.FireFightingWorks;
using LeadThing.AbpZeroTemplate.FireFightingWorks.Dtos;
using LeadThing.AbpZeroTemplate.CaseCategorys;
using LeadThing.AbpZeroTemplate.CaseCategorys.Dtos;
using System.Text;

namespace LeadThing.AbpZeroTemplate.Web.Controllers
{
    public class HomeController : AbpZeroTemplateControllerBase
    {
        private readonly IPerRequestSessionCache _sessionCache;
        private readonly IAreaAppService _areaService;
        private readonly IDisputeInformationAppService _disputeInformationAppService;
        private readonly ICallPoliceAppService _callPoliceAppService;
        private readonly IRoleAppService _roleAppService;
        private readonly IUserAppService _userAppService;
        private readonly ISpecialPersonAppService _specialPersonAppService;
        private readonly ILawsRegulationsAppService _lawsRegulationsAppService;
        private readonly ICameraManageAppService _cameraManageAppService;
        private readonly IUserTrajectoryAppService _userTrajectoryAppService;
        private readonly IBasicPersonAppService _basicPersonAppService;
        private readonly IFireFightingWorkAppService _fireFightingWorkAppService;
        private readonly ICaseCategoryAppService _caseCategoryAppService;

        public HomeController(IPerRequestSessionCache sessionCache,
            IAreaAppService areaService,
            IDisputeInformationAppService disputeInformationAppService,
            ICallPoliceAppService callPoliceAppService,
            IRoleAppService roleAppService,
            IUserAppService userAppService,
            ISpecialPersonAppService specialPersonAppService,
            ILawsRegulationsAppService lawsRegulationsAppService,
            ICameraManageAppService cameraManageAppService,
            IUserTrajectoryAppService userTrajectoryAppService,
            IBasicPersonAppService basicPersonAppService,
            IFireFightingWorkAppService fireFightingWorkAppService,
            ICaseCategoryAppService caseCategoryAppService)
        {
            _sessionCache = sessionCache;
            _areaService = areaService;
            _disputeInformationAppService = disputeInformationAppService;
            _callPoliceAppService = callPoliceAppService;
            _roleAppService = roleAppService;
            _userAppService = userAppService;
            _specialPersonAppService = specialPersonAppService;
            _lawsRegulationsAppService = lawsRegulationsAppService;
            _cameraManageAppService = cameraManageAppService;
            _userTrajectoryAppService = userTrajectoryAppService;
            _basicPersonAppService = basicPersonAppService;
            _fireFightingWorkAppService = fireFightingWorkAppService;
            _caseCategoryAppService = caseCategoryAppService;
        }


        public ActionResult Index()
        {
            return View();
        }

        public async Task<ActionResult> MapIndex()
        {
            var mapIndexViewModel = new MapIndexViewModel();

            if (AbpSession.UserId.HasValue)
            {
                mapIndexViewModel.LoginInformations = AsyncHelper.RunSync(() => _sessionCache.GetCurrentLoginInformationsAsync());
            }
            else
            {
                Response.Redirect("/Account/Login");
            }

            return View(mapIndexViewModel);
        }

        public ActionResult MapMain()
        {
            return View();
        }

        /// <summary>
        /// 获取角色名称
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetRoleName()
        {
            string result = string.Empty;
            if (AbpSession.UserId.HasValue)
            {
                GetRolesInput roleInput = new GetRolesInput() { UserId = AbpSession.UserId.Value };
                var role = await _roleAppService.GetRolesByUserId(roleInput);
                result = role.DisplayName;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult MapAPI()
        {
            return View();
        }

        public ActionResult MapAPII()
        {
            return View();
        }

        public ActionResult EnvCityStatistic()
        {
            return View();
        }

        public ActionResult Test()
        {
            var words = Request.QueryString["words"];//搜索关键字
            var result = "";
            var querytype = "";
            if (Request.QueryString["class"] != null)
            {
                querytype = Request.QueryString["class"].ToString();
            }
            int pageIndex = 1;
            int.TryParse(Request.QueryString["pageIndex"], out pageIndex);
            int pageSize = 10;
            int.TryParse(Request.QueryString["pageSize"], out pageSize);

            GetAreaInput input = new GetAreaInput();
            List<TownTwo> TownTwoList = new List<TownTwo>();

            switch (querytype)
            {
                case "citycenter":
                    result = "{\"status\":\"ok\",\"result\":{\"curpage\":1,\"pagecount\":200,\"curresult\":50,\"total\":50,\"entitytotal\":0,\"time\":\"0.377\",\"bound\":\"118.813229,35.525656;118.944564,35.674979\",\"features\":[{\"id\":\"1\",\"lsid\":\"7CEEA20B\",\"name\":\"莒县社会矛盾调处中心\",\"lng\":\"118.83181079961668\",\"lat\":\"35.5806854273537\",\"district\":\"371122000\",\"district_text\":\"山东省>日照市>莒县\",\"navid\":\"55142079\",\"class_id\":\"5380\",\"class_text\":\"住宿>旅馆、招待所\"}]}}";
                    break;
                case "townscenter":

                    input.Level = 1;
                    input.FilterText = words;
                    input.SkipCount = (pageIndex - 1) * pageSize;
                    input.MaxResultCount = pageSize;
                    var townList = _areaService.GetAreaByWhereAsyncLoadPage(input);

                    foreach (var item in townList.Items)
                    {
                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Title,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.Title,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            house_holds = item.Households,
                            person_num = item.PersonNum,
                            content = item.Remarks == null ? "暂无介绍" : item.Remarks,

                            type = "local"
                        };
                        TownTwoList.Add(model);
                    }

                    TownOneLayer resultModelOne = new TownOneLayer() { curpage = pageIndex, pagecount = pageSize, curresult = townList.TotalCount, total = townList.TotalCount, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelOne = new TownsCenterViewModel() { status = "ok", result = resultModelOne };
                    result = JsonConvert.SerializeObject(viewModelOne);
                    break;
                case "communitycenter":

                    input.Level = 2;
                    input.FilterText = words;
                    input.SkipCount = (pageIndex - 1) * pageSize;
                    input.MaxResultCount = pageSize;
                    var communityList = _areaService.GetAreaByWhereAsyncLoadPage(input);

                    foreach (var item in communityList.Items)
                    {
                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Title,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.Address + item.Title,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            house_holds = item.Households,
                            person_num = item.PersonNum,
                            content = item.Remarks == null ? "暂无介绍" : item.Remarks,
                            type = "local"
                        };
                        TownTwoList.Add(model);
                    }

                    TownOneLayer resultModelTwo = new TownOneLayer() { curpage = pageIndex, pagecount = pageSize, curresult = communityList.TotalCount, total = communityList.TotalCount, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelTwo = new TownsCenterViewModel() { status = "ok", result = resultModelTwo };
                    result = JsonConvert.SerializeObject(viewModelTwo);
                    break;
                case "smallcenter":

                    input.Level = 3;
                    input.FilterText = words;
                    input.SkipCount = (pageIndex - 1) * pageSize;
                    input.MaxResultCount = pageSize;
                    var smallList = _areaService.GetAreaByWhereAsyncLoadPage(input);

                    foreach (var item in smallList.Items)
                    {
                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Title,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.Address + item.Title,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            house_holds = item.Households,
                            person_num = item.PersonNum,
                            content = item.Remarks == null ? "暂无介绍" : item.Remarks,
                            type = "local"
                        };
                        TownTwoList.Add(model);
                    }

                    TownOneLayer resultModelThree = new TownOneLayer() { curpage = pageIndex, pagecount = pageSize, curresult = smallList.TotalCount, total = smallList.TotalCount, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelThree = new TownsCenterViewModel() { status = "ok", result = resultModelThree };
                    result = JsonConvert.SerializeObject(viewModelThree);
                    break;
                case "patrolman":

                    var userType = Request.QueryString["userType"];
                    GetUsersInput userInput = new GetUsersInput() { Filter = words, UserType = userType, SkipCount = (pageIndex - 1) * pageSize, MaxResultCount = pageSize };
                    var userList = _userAppService.GetAllUsersLoadPage(userInput);

                    foreach (var item in userList.Items)
                    {
                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Name,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.TownTitle + item.AreaTitle + item.VillageTitle,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            type = "patrolman",
                            telephone = item.PhoneNumber,
                            UserType = item.UserType
                        };
                        TownTwoList.Add(model);
                    }

                    TownOneLayer resultModelUser = new TownOneLayer() { curpage = pageIndex, pagecount = pageSize, curresult = userList.TotalCount, total = userList.TotalCount, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelUser = new TownsCenterViewModel() { status = "ok", result = resultModelUser };
                    result = JsonConvert.SerializeObject(viewModelUser);

                    break;
                case "specialpeople":

                    GetSpecialPersonInput SpecialPersonInput = new GetSpecialPersonInput() { Filter = words, SkipCount = (pageIndex - 1) * pageSize, MaxResultCount = pageSize };
                    var specialPersonList = _specialPersonAppService.GetAllSpecialPersonLoadPage(SpecialPersonInput);

                    foreach (var item in specialPersonList.Items)
                    {
                        SpecialPersonViewModel specialPersonViewModel = new SpecialPersonViewModel()
                        {
                            Name = item.Name,
                            IDCard = item.IDCard,
                            Address = item.Address,
                            SexName = item.SexName,
                            PoliticsName = item.PoliticsName,
                            HealthName = item.HealthName,
                            CultureName = item.CultureName,
                            TownTitle = item.TownTitle,
                            AreaTitle = item.AreaTitle,
                            VillageTitle = item.VillageTitle,
                            NationName = item.NationName,
                            PersonTypeName = item.PersonTypeName
                        };

                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Name,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.TownTitle + item.AreaTitle + item.VillageTitle + item.Address,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            type = "specialpeople",
                            telephone = item.Phone,
                            specialPersonViewModel = specialPersonViewModel
                        };
                        TownTwoList.Add(model);
                    }

                    TownOneLayer resultModelSpecialPerson = new TownOneLayer() { curpage = pageIndex, pagecount = pageSize, curresult = specialPersonList.TotalCount, total = specialPersonList.TotalCount, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelSpecialPerson = new TownsCenterViewModel() { status = "ok", result = resultModelSpecialPerson };
                    result = JsonConvert.SerializeObject(viewModelSpecialPerson);

                    break;
                case "lawsRegulationss"://法律法规

                    GetLawsRegulationsInput LawsRegulationsInput = new GetLawsRegulationsInput() { Filter = words };
                    var lawsRegulationsList = _lawsRegulationsAppService.GetAllLawsRegulationsLoadPage(LawsRegulationsInput);
                    List<LawsRegulationsViewModel> lawsRegulationsViewList = new List<LawsRegulationsViewModel>();
                    foreach (var item in lawsRegulationsList)
                    {
                        LawsRegulationsViewModel lawsRegulationsModel = new LawsRegulationsViewModel()
                        {
                            title = item.Title,
                            content = item.Content
                        };
                        lawsRegulationsViewList.Add(lawsRegulationsModel);
                    }
                    result = JsonConvert.SerializeObject(lawsRegulationsViewList);
                    break;
                case "basicPerson":
                    GetBasicPersonInput BasicPersonInput = new GetBasicPersonInput() { FilterText = words, SkipCount = (pageIndex - 1) * pageSize, MaxResultCount = pageSize };
                    var basicPersonList = _basicPersonAppService.GetAllBasicPersonLoadPage(BasicPersonInput);
                    List<BasicPersonViewModel> basicPersonViewList = new List<BasicPersonViewModel>();
                    foreach (var item in basicPersonList.Items)
                    {
                        BasicPersonViewModel basicPersonViewModel = new BasicPersonViewModel()
                        {
                            Name = item.Name,
                            IDCard = item.IDCard,
                            TotalPopulation = item.TotalPopulation,
                            Relationship = item.Relationship,
                            Industry = item.Industry,
                            ContractField = item.ContractField,
                            ResponsibilityField = item.ResponsibilityField,
                            HouseNumber = item.HouseNumber,
                            Building = item.Building,
                            Bungalow = item.Bungalow,
                            TownTitle = item.TownTitle,
                            AreaTitle = item.AreaTitle,
                            VillageTitle = item.VillageTitle,
                            SexName = item.SexName,
                            MartyrName = item.MartyrName,
                            AllowanceName = item.AllowanceName,
                            LonelyName = item.LonelyName,
                            ElderlyName = item.ElderlyName,
                            FiveGuaranteesName = item.FiveGuaranteesName,
                            PoliticsName = item.PoliticsName
                        };

                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Name,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.TownTitle + item.AreaTitle + item.VillageTitle,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            type = "basicPerson",
                            basicPersonViewModel = basicPersonViewModel
                        };
                        TownTwoList.Add(model);
                    }
                    TownOneLayer resultModelBasicPerson = new TownOneLayer() { curpage = pageIndex, pagecount = pageSize, curresult = basicPersonList.TotalCount, total = basicPersonList.TotalCount, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelBasicPerson = new TownsCenterViewModel() { status = "ok", result = resultModelBasicPerson };
                    result = JsonConvert.SerializeObject(viewModelBasicPerson);
                    break;
                case "fireFightingWork"://消防工作
                    GetFireFightingWorkInput fireFightingWorkModel = new GetFireFightingWorkInput() { Filter = words };
                    var fireFightingWorkList = _fireFightingWorkAppService.GetAllFireFightingWorksLoadPage(fireFightingWorkModel);
                    List<FireFightingWorkViewModel> fireFightingWorkViewList = new List<FireFightingWorkViewModel>();
                    foreach (var item in fireFightingWorkList)
                    {
                        FireFightingWorkViewModel fireFightingWorkViewModel = new FireFightingWorkViewModel()
                        {
                            Title = item.Title,
                            TownTitle = item.TownTitle,
                            AreaTitle = item.AreaTitle,
                            VillageTitle = item.VillageTitle,
                            Desc = item.Desc,
                            fileList = item.fileList
                        };

                        TownTwo model = new TownTwo()
                        {
                            id = item.Id.ToString(),
                            lsid = item.Id.ToString(),
                            name = item.Title,
                            lng = item.XPoint,
                            lat = item.YPoint,
                            district = "371122000",
                            district_text = "山东省>日照市>莒县>" + item.TownTitle + item.AreaTitle + item.VillageTitle,
                            navid = "55142079",
                            class_id = "5380",
                            class_text = "住宿>旅馆、招待所",
                            type = "fireFightingWork",
                            fireFightingWorkViewModel = fireFightingWorkViewModel
                        };
                        TownTwoList.Add(model);
                    }

                    TownOneLayer resultModelFireFightingWork = new TownOneLayer() { curpage = 1, pagecount = 200, curresult = 50, total = 50, entitytotal = 0, time = "0.377", bound = "118.813229,35.525656;118.944564,35.674979", features = TownTwoList };
                    TownsCenterViewModel viewModelFireFightingWork = new TownsCenterViewModel() { status = "ok", result = resultModelFireFightingWork };
                    result = JsonConvert.SerializeObject(viewModelFireFightingWork);
                    break;
                default:
                    result = result = "{\"status\":\"ok\",\"result\":{\"curpage\":1,\"pagecount\":200,\"curresult\":50,\"total\":50,\"entitytotal\":0,\"time\":\"0.377\",\"bound\":\"118.813229,35.525656;118.944564,35.674979\",\"features\":[]}}";
                    break;
            }

            return Content(result);
        }

        public async Task<JsonResult> Test2()
        {
            object result = "";
            var querytype = "";
            if (Request.QueryString["type"] != null)
                querytype = Request.QueryString["type"].ToString();
            switch (querytype)
            {
                case "weather"://综治中心

                    var _level = Convert.ToInt32(Request.QueryString["level"]);
                    GetAreaInput areaInput = new GetAreaInput() { Level = _level };
                    result = (await _areaService.GetAreaByWhereAsync(areaInput)).Items;
                    break;
                case "road"://矛盾纠纷
                    GetDisputeInformationInput disInput = new GetDisputeInformationInput();
                    result = (await _disputeInformationAppService.GetDisputeInformationsByWhereAsync(disInput)).Items;
                    break;
                case "enviro":
                    result = "[{\"Name\":null,\"GetTime\":[\"刘官庄镇\",\"浮来山镇\",\"小店镇\",\"陵阳镇\",\"安庄镇\",\"城阳街道\",\"夏庄镇\",\"长岭镇\",\"寨里河镇\",\"龙山镇\",\"店子集镇\",\"峤山镇\",\"桑园镇\",\"招贤镇\",\"东莞镇\",\"库山乡\",\"幕山镇\"],\"Excellent\":[18,82,15,21,27,76,25,28,32,134,76,21,26,14,6,20,15],\"Good\":[141,138,149,140,150,142,151,148,147,96,121,149,143,133,125,133,132],\"Slight\":[62,18,54,60,45,23,44,50,45,11,34,46,53,63,76,62,60],\"Middle\":[14,3,19,11,11,2,14,14,15,3,9,20,15,16,18,18,24],\"Servere\":[8,4,6,12,11,2,9,3,6,1,4,7,7,15,16,9,12],\"Serious\":[2,0,2,1,1,0,2,2,0,0,1,2,1,4,4,3,2]},{\"Name\":null,\"GetTime\":[],\"Excellent\":[53,144,50,52,70,150,67,74,84,179,101,54,78,47,34,40,40],\"Good\":[130,83,141,132,124,78,123,126,109,58,104,131,113,128,130,130,125],\"Slight\":[44,13,34,40,31,14,34,28,36,6,28,33,35,39,45,48,45],\"Middle\":[10,2,12,10,10,1,10,9,10,2,9,18,10,14,18,14,21],\"Servere\":[7,3,7,11,9,2,9,7,6,0,3,8,9,13,16,11,14],\"Serious\":[1,0,1,0,1,0,2,1,0,0,0,1,0,4,2,2,0]}]";
                    break;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult MapLogin()
        {
            return View();
        }

        public ActionResult ChangeSpecialSympal()
        {
            return View();
        }

        public ActionResult MapChoosePos()
        {
            return View();
        }

        /// <summary>
        /// 乡镇纠纷统计
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetTownbarChart()
        {
            GetDisputeInformationInput input = new GetDisputeInformationInput() { DisputeTypeID = 0 };
            var list = await _disputeInformationAppService.GetTownPie(input);

            return Json(list.Items, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 柱状图数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetBarChart()
        {
            var list = await _disputeInformationAppService.GetBarChart();
            return Json(list.Items, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 饼图数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetPie()
        {
            var list = await _disputeInformationAppService.GetPie();
            return Json(list.Items, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取未受理的一键报警
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetCallPolices()
        {
            GetCallPoliceInput input = new GetCallPoliceInput() { Status = 8 };
            var list = await _callPoliceAppService.GetCallPolicesByWhereAsync(input);
            return Json(list.Items, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取所有好视通会议室
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAllRoomInforList(string userName)
        {
            IWebserviceJaxwsService webService = new IWebserviceJaxwsService();
            var dataXML = webService.getRoominfoByUserName(userName, "3025495AEE146DA3864AB81BAAF79A3E");
            var code = "";//返回码
            var msg = "";

            XmlDocument dom = new XmlDocument();
            dom.LoadXml(dataXML);
            XmlNode nodeCode = dom.SelectSingleNode("//code");//返回码
            code = nodeCode.InnerText;
            XmlNode nodeMsg = dom.SelectSingleNode("//msg");
            msg = nodeMsg.InnerText;
            List<HstMeetingRoomViewModel> roomList = new List<HstMeetingRoomViewModel>();

            if (code != "0000")
            {
                return Json(roomList, JsonRequestBehavior.AllowGet);
            }

            //获取节点列表  
            XmlNodeList topM = dom.SelectNodes("//room");

            foreach (XmlElement node in topM)
            {
                HstMeetingRoomViewModel roomModel = new HstMeetingRoomViewModel();

                #region 赋值
                roomModel.curUserCount = node.GetElementsByTagName("curUserCount")[0].InnerText;
                roomModel.hopeEndTime = node.GetElementsByTagName("hopeEndTime")[0].InnerText;
                roomModel.hopeStartTime = node.GetElementsByTagName("hopeStartTime")[0].InnerText;
                roomModel.maxUserCount = node.GetElementsByTagName("maxUserCount")[0].InnerText;
                roomModel.roomId = node.GetElementsByTagName("roomId")[0].InnerText;
                roomModel.roomName = node.GetElementsByTagName("roomName")[0].InnerText;
                roomModel.roomType = node.GetElementsByTagName("roomType")[0].InnerText;
                roomModel.verifyMode = node.GetElementsByTagName("verifyMode")[0].InnerText;
                #endregion

                roomList.Add(roomModel);
            }

            return Json(roomList);
        }

        /// <summary>
        /// 视频监控摄像头数据同步
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> DataSynchronization()
        {
            Random rd = new Random();
            XmlDocument dom = new XmlDocument();
            dom.Load("D:\\组织树.xml");

            //获取组织树、部门节点
            XmlNodeList topM = dom.SelectNodes("//Department[@coding]");

            //清空摄像头表数据
            if (topM.Count > 0)
            {
                var count = _cameraManageAppService.DeleteAllCameraManages();
            }

            for (int i = 0; i < topM.Count; i++)
            {
                XmlNode node = topM[i];
                string cameraId = string.Empty;//摄像头id
                string XPoint = string.Empty;//经度
                string YPoint = string.Empty;//维度

                if (node.Attributes["coding"] == null)
                {
                    continue;
                }

                cameraId = node.Attributes["coding"].Value;
                GetAreaInput input = new GetAreaInput() { CameraID = cameraId };
                var areaModel = await _areaService.GetAreaByCameraIdAsync(input);
                if (areaModel == null && cameraId != "001001")
                {
                    continue;
                }
                //加入001001这个特殊情况
                if (cameraId == "001001")
                {
                    XPoint = "118.83002";
                    YPoint = "35.5811";
                }
                else
                {
                    XPoint = areaModel.XPoint;
                    YPoint = areaModel.YPoint;
                }
                try
                {

                    //坐标是否合理
                    if (string.IsNullOrWhiteSpace(XPoint) || double.Parse(XPoint) == 0 || string.IsNullOrWhiteSpace(YPoint) || double.Parse(YPoint) == 0)
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    continue;
                }

                //获取Channel监控节点列表  
                XmlNodeList twoM = node.SelectNodes("Channel");
                for (int j = 0; j < twoM.Count; j++)
                {
                    XmlNode twoNode = twoM[j];
                    string channelId = twoNode.Attributes["id"].Value;

                    XmlNode threeNode = dom.SelectSingleNode($"//Channel[@id='{channelId}'][@name]");

                    if (threeNode == null)
                    {
                        continue;
                    }
                    CameraManageEditDto addModel = new CameraManageEditDto();
                    addModel.CameraId = threeNode.Attributes["id"].Value;

                    if (threeNode.Attributes["name"] != null)
                        addModel.CameraName = threeNode.Attributes["name"].Value;
                    if (threeNode.Attributes["status"] != null)
                        addModel.Status = threeNode.Attributes["status"].Value;
                    if (threeNode.Attributes["channelType"] != null)
                        addModel.ChannelType = threeNode.Attributes["channelType"].Value;
                    if (threeNode.Attributes["channelSN"] != null)
                        addModel.ChannelSN = threeNode.Attributes["channelSN"].Value;
                    if (threeNode.Attributes["rights"] != null)
                        addModel.Rights = threeNode.Attributes["rights"].Value;
                    if (threeNode.Attributes["cameraType"] != null)
                        addModel.CameraType = threeNode.Attributes["cameraType"].Value;
                    if (threeNode.Attributes["ctrlId"] != null)
                        addModel.CtrlId = threeNode.Attributes["ctrlId"].Value;

                    StringBuilder xsb = new StringBuilder();
                    for (int h = 0; h < 2; h++)
                    {
                        xsb.Append(rd.Next(1, 10).ToString());
                    }

                    StringBuilder ysb = new StringBuilder();
                    for (int h = 0; h < 2; h++)
                    {
                        ysb.Append(rd.Next(1, 10).ToString());
                    }

                    if (YPoint.Length > 2)
                    {
                        addModel.Longitude = YPoint.Substring(0, YPoint.Length - 2) + xsb.ToString();
                    }

                    if (XPoint.Length > 2)
                    {
                        addModel.Latitude = XPoint.Substring(0, XPoint.Length - 2) + ysb.ToString();
                    }

                    //if (threeNode.Attributes["latitude"] != null)
                    //    addModel.Latitude = threeNode.Attributes["latitude"].Value;
                    //if (threeNode.Attributes["longitude"] != null)
                    //    addModel.Longitude = threeNode.Attributes["longitude"].Value;
                    if (threeNode.Attributes["viewDomain"] != null)
                        addModel.ViewDomain = threeNode.Attributes["viewDomain"].Value;
                    if (threeNode.Attributes["cameraFunctions"] != null)
                        addModel.CameraFunctions = threeNode.Attributes["cameraFunctions"].Value;
                    if (threeNode.Attributes["multicastIp"] != null)
                        addModel.MulticastIp = threeNode.Attributes["multicastIp"].Value;
                    if (threeNode.Attributes["multicastPort"] != null)
                        addModel.MulticastPort = threeNode.Attributes["multicastPort"].Value;
                    if (threeNode.Attributes["nvrChnlIp"] != null)
                        addModel.NvrChnlIp = threeNode.Attributes["nvrChnlIp"].Value;
                    if (threeNode.Attributes["channelRemoteType"] != null)
                        addModel.ChannelRemoteType = threeNode.Attributes["channelRemoteType"].Value;
                    if (threeNode.Attributes["subMulticastIp"] != null)
                        addModel.SubMulticastIp = threeNode.Attributes["subMulticastIp"].Value;
                    if (threeNode.Attributes["subMulticastPort"] != null)
                        addModel.SubMulticastPort = threeNode.Attributes["subMulticastPort"].Value;


                    if (cameraId == "001001")
                    {
                        addModel.TownID = 0;
                        addModel.AreaID = 0;
                        addModel.VillageID = 0;
                    }
                    else
                    {
                        addModel.TownID = areaModel.TownID;
                        addModel.AreaID = areaModel.AreaID;
                        addModel.VillageID = areaModel.VillageID;
                    }
                    //不存在就添加
                    var re = await _cameraManageAppService.CreateCameraManageAsync(addModel);
                }
            }
            return Json("");
        }

        /// <summary>
        /// 获取全部摄像机数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllCamera()
        {
            var list = _cameraManageAppService.GetAllCameraManages();
            List<CameraManageMapViewModel> reList = new List<CameraManageMapViewModel>();
            foreach (var item in list)
            {
                CameraManageMapViewModel model = new CameraManageMapViewModel()
                {
                    name = item.CameraName,
                    x = item.Latitude,
                    y = item.Longitude,
                    request = item.CameraId,
                    type = "3"
                };
                reList.Add(model);
            }

            return Json(reList);
        }

        /// <summary>
        /// 根据UserId获取用户巡查轨迹
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserTrajectoryByUserId(int userId)
        {
            GetUserTrajectoryInput input = new GetUserTrajectoryInput() { UserId = userId };
            var list = _userTrajectoryAppService.GetUserTrajectoryByUserId(input);

            return Json(list);
        }

        /// <summary>
        /// 获取法律法规
        /// </summary>
        /// <param name="top"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetLawsRegulationses(int top)
        {
            GetLawsRegulationsInput LawsRegulationsInput = new GetLawsRegulationsInput() { Top = top };
            var lawsRegulationsList = _lawsRegulationsAppService.GetAllLawsRegulationsLoadPage(LawsRegulationsInput);
            return Json(lawsRegulationsList);
        }

        /// <summary>
        /// 获取全部矛盾纠纷案例数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllCaseCategorys()
        {

            GetCaseCategoryInput caseCategoryInput = new GetCaseCategoryInput() { ParentID = 0, Layer = 1 };
            var oneMenuList = _caseCategoryAppService.GetAllCaseCategorysLoadPage(caseCategoryInput);

            List<CaseCategoryViewModel> oneList = new List<CaseCategoryViewModel>();

            foreach (var item in oneMenuList)
            {
                CaseCategoryViewModel oneLayer = new CaseCategoryViewModel();
                oneLayer.id = Convert.ToInt32(item.Id);
                oneLayer.text = item.Title;
                oneLayer.layer = item.Layer;
                oneLayer.content = "";

                #region 二级菜单

                caseCategoryInput.ParentID = oneLayer.id;
                caseCategoryInput.Layer = 2;
                var twoMenuList = _caseCategoryAppService.GetAllCaseCategorysLoadPage(caseCategoryInput);
                List<CaseCategoryTwoLayer> twoList = new List<CaseCategoryTwoLayer>();
                foreach (var twoItem in twoMenuList)
                {
                    CaseCategoryTwoLayer twoLayer = new CaseCategoryTwoLayer();
                    twoLayer.id = Convert.ToInt32(twoItem.Id);
                    twoLayer.text = twoItem.Title;
                    twoLayer.layer = twoItem.Layer;
                    twoLayer.content = "";

                    #region 三级菜单
                    caseCategoryInput.ParentID = twoLayer.id;
                    caseCategoryInput.Layer = 3;
                    var threeMenuList = _caseCategoryAppService.GetAllCaseCategorysLoadPage(caseCategoryInput);
                    List<CaseCategoryThreeLayer> threeList = new List<CaseCategoryThreeLayer>();
                    foreach (var threeItem in threeMenuList)
                    {
                        CaseCategoryThreeLayer threeLayer = new CaseCategoryThreeLayer();
                        threeLayer.id = Convert.ToInt32(threeItem.Id);
                        threeLayer.text = threeItem.Title;
                        threeLayer.layer = threeItem.Layer;
                        threeLayer.content = threeItem.Content;

                        threeList.Add(threeLayer);
                    }
                    #endregion
                    twoLayer.nodes = threeList;
                    twoList.Add(twoLayer);
                }

                #endregion
                oneLayer.nodes = twoList;

                oneList.Add(oneLayer);
            }

            return Json(oneList);
        }

        /// <summary>
        /// 根据层级统计网格人口
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPersonPercentageByLevelLoadPage(int id, int level, int parentId)
        {
            GetAreaInput input = new GetAreaInput() { Level = level, ParentId = parentId };
            var reList = _areaService.GetPersonPercentageByLevelLoadPage(input);

            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (var item in reList)
            {
                if (item.Id == id)
                {
                    sb.Append("{");
                    sb.AppendFormat(" name: '{0}',y: {1},sliced: true,selected: true ", item.Title, item.Percentage);
                    sb.Append("},");
                }
                else
                {
                    sb.AppendFormat("['{0}', {1}],", item.Title, item.Percentage);
                }
            }
            sb.Append("]");

            return Json(sb.ToString());
        }

        /// <summary>
        /// 根据层级统计矛盾纠纷人数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="level"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetSumPersonByLevelLoadPage(int id, int level, int parentId)
        {
            GetAreaInput input = new GetAreaInput() { Level = level, ParentId = parentId };
            var reList = _areaService.GetSumPersonByLevelLoadPage(input);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (var item in reList)
            {
                sb.AppendFormat("['{0}', {1}],", item.Title, item.SumPerson);
            }
            sb.Append("]");
            return Json(sb.ToString());
        }

        /// <summary>
        /// 根据层级统计特殊人群人数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="level"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetSumSpecialPerson(int id, int level, int parentId)
        {
            GetAreaInput input = new GetAreaInput() { Level = level, ParentId = parentId };
            var reList = _areaService.GetSumSpecialPersonLoadPage(input);
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (var item in reList)
            {
                sb.AppendFormat("['{0}', {1}],", item.Title, item.SumPerson);
            }
            sb.Append("]");
            return Json(sb.ToString());
        }

        /// 发送请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">参数格式 “name=王武&pass=123456”</param>
        /// <returns></returns>
        public static string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";
            try
            {
                System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
                httpRquest.Method = "GET";
                //这行代码很关键，不设置ContentType将导致后台参数获取不到值
                httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                //httpRquest.ContentLength = dataArray.Length;

                System.Net.WebResponse response = httpRquest.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return backMsg;
        }

        public JsonResult GetCurrentIP()
        {
            string userIP;
            // HttpRequest Request = HttpContext.Current.Request;  
            System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request; // 如果使用代理，获取真实IP  
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                userIP = Request.ServerVariables["REMOTE_ADDR"];
            else
                userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (userIP == null || userIP == "")
                userIP = Request.UserHostAddress;
            return Json(userIP, JsonRequestBehavior.AllowGet);
        }
    }
}